package com.yanqu.road.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.entity.web.HttpJsonWebParam;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

public class BaseJsonHttpServlet extends BaseHttpServlet {

    private Logger logger = LogManager.getLogger(this.getClass().getName());

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        parseRequest(request);
    }

    /**
     * 解析http参数
     * @param request
     * @return
     */
    public HttpJsonWebParam parseRequest(HttpServletRequest request) {
        HttpJsonWebParam httpJsonWebParam = new HttpJsonWebParam();
        try{
            String requestContent = getRequestContent(request);
            logger.info("request:{}", requestContent);
            JSONObject paramObj = JSONObject.parseObject(requestContent);

            httpJsonWebParam.setRequestContent(requestContent);
            httpJsonWebParam.setParamObj(paramObj);

        } catch (Exception e) {
            logger.error("parseRequest error:", e);
        }
        return httpJsonWebParam;
    }

    protected String getRequestContent(HttpServletRequest request) throws IOException {
        BufferedReader streamReader = new BufferedReader( new InputStreamReader(request.getInputStream(), StandardCharsets.UTF_8));
        StringBuilder responseStrBuilder = new StringBuilder();
        String inputStr;
        while ((inputStr = streamReader.readLine()) != null) {
            responseStrBuilder.append(inputStr);
        }
        return responseStrBuilder.toString();
    }

    public JSONObject getResultObj(int state, String msg){
        JSONObject resultObj = new JSONObject();
        resultObj.put("state", state);
        resultObj.put("msg", msg);
        return resultObj;
    }

    public void sendResult(HttpServletResponse response, int state, String msg){
        JSONObject resultObj = getResultObj(state, msg);
        sendMessage(response, resultObj.toJSONString());
    }

    public JSONObject get37ResultObj(int result, String msg){
        JSONObject resultObj = new JSONObject();
        resultObj.put("result", result);
        resultObj.put("msg", msg);
        return resultObj;
    }

    public void send37Result(HttpServletResponse response, int result, String msg){
        JSONObject resultObj = get37ResultObj(result, msg);
        sendMessage(response, resultObj.toJSONString());
    }
}
